import React from 'react';
import type {UploadFile, UploadProps} from 'antd';
import {message, Upload} from "antd";
import {InboxOutlined} from "@ant-design/icons";
import {uploadFileUsingPost} from "@/services/backend/fileController";

const {Dragger} = Upload;

interface Props {
  biz: string;
  onChange?: (fileList: UploadFile[]) => void;
  value?: UploadFile[]; // 上传文件时的固定类型(项目中文件为代码生成器的产物zip)
  description?: string
}

/**
 * 文件上传组件
 * @constructor
 */
const FileUploader: React.FC<Props> = (props: Props) => {

  const {biz, value, description, onChange} = props;
  const [loading, setLoading] = React.useState<boolean>(false);

  const uploadProps: UploadProps = {
    name: 'file',
    multiple: false,
    listType: "text",
    maxCount: 1,
    fileList: value,
    disabled: loading,
    onChange({fileList}){
      onChange?.(fileList)
    },
    customRequest: async (fileObj: any) => {
      setLoading(true);
      try {
        const res = await uploadFileUsingPost({biz}, {}, fileObj.file);
        fileObj.onSuccess(res.data);
      } catch (error: any) {
        message.error("上传失败，" + error.message);
        fileObj.onError(error);
      }
      setLoading(false);
    },
  };

  return (
    <Dragger {...uploadProps}>
      <p className="ant-upload-drag-icon">
        <InboxOutlined/>
      </p>
      <p className="ant-upload-text">点击或拖拽文件上传</p>
      <p className="ant-upload-hint">{description}</p>
    </Dragger>
  );
};
export default FileUploader;
